import Vue from 'vue';
import router from './router';
import store from './store';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { ACCESS_TOKEN, INDEX_MAIN_PAGE_PATH } from '@/store/mutation-types'
import { generateIndexRouter } from '@/utils/util'

router.beforeEach((to, from, next) => { 
    NProgress.start();
    if (Vue.ls.get(ACCESS_TOKEN)) {
        next({ path: INDEX_MAIN_PAGE_PATH });
        NProgress.done();
    } else { 
        if (store.getters.permissionList.length === 0) { 
            store.dispatch('GetPermissionList').then(res => { 
                const menuData = res.result.menu;
                let constRoutes = [];
                constRoutes = generateIndexRouter(menuData);
                store.dispatch('UpdateAppRouter',  { constRoutes }).then(() => {
                    router.addRoutes(store.getters.addRouters)
                    const redirect = decodeURIComponent(from.query.redirect || to.path)
                    if (to.path === redirect) {
                      next({ ...to, replace: true })
                    } else {
                      // 跳转到目的路由
                      next({ path: redirect })
                    }
                  })
            })
        }else {
          next()
        }
    } 
})

router.afterEach(() => {
  NProgress.done()
})